<template>
  <el-form
    status-icon
    ref="form"
    :rules="rules"
    :model="form"
    class="firstForm"
    label-width="120px"
  >
    <el-form-item v-show="false" label="固定资产id">
      <el-input :style="fixWidth" :disabled="true" placeholder="请输入" v-model="form.assetsId"></el-input>
    </el-form-item>
    <el-row>
      <el-col :span="12">
        <el-form-item prop="assetsName" label="资产名称">
          <el-autocomplete
            :style="fixWidth"
            v-model="form.assetsName"
            :fetch-suggestions="(queryString, cb) => supplierQueryAsync(queryString, cb, false)"
            placeholder="请输入资产名称"
            @select="handleAssetsSelect"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="categoryId" label="资产类别">
          <type-select
            :selectValue="form.categoryId"
            :selectStyle="fixWidth"
            ref="typeSelect"
            @select="value => handleSelect('categoryId', value)"
            v-model="form.categoryId"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态" prop="assetsState">
          <el-select clearable :style="fixWidth" v-model="form.assetsState" placeholder="请选择状态">
            <el-option :value="0" label="正常" />
            <el-option :value="1" label="遗失" />
            <el-option :value="2" label="标签破损" />
            <el-option :value="3" label="维修" />
            <el-option :value="4" label="报废" />
            <el-option :value="5" label="违规异动" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="品牌">
          <el-input :style="fixWidth" type="text" v-model="form.brand" placeholder="请输入品牌名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="规格型号">
          <el-input
            :style="fixWidth"
            :readOnly="assetsNameDisable"
            placeholder="请输入规格型号"
            v-model="form.specification"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="计量单位">
          <el-input
            :style="fixWidth"
            :readOnly="assetsNameDisable"
            placeholder="请输入计量单位"
            v-model="form.unit"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="供应商">
          <el-autocomplete
            :style="fixWidth"
            v-model="form.supplier"
            :fetch-suggestions="(queryString, cb) => supplierQueryAsync(queryString, cb, true, 'supplier')"
            placeholder="请输入供应商名称"
            @select="value => supplierSelect(value, 'supplier', 'supplierCode')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="生产厂家">
          <el-autocomplete
            :style="fixWidth"
            class="factory-autocomplete"
            v-model="form.factory"
            :disabled="assetsNameDisable"
            :fetch-suggestions="(queryString, cb) => supplierQueryAsync(queryString, cb, true, 'factory')"
            placeholder="请输入供应商名称"
            @select="value => supplierSelect(value, 'factory', 'factoryCode')"
          />
          <!-- <el-input :style="fixWidth" placeholder="请输入生产厂家" v-model="form.factory" /> -->
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="购买日期">
          <el-date-picker
            value-format="yyyy-MM-dd"
            :style="fixWidth"
            type="date"
            placeholder="请选择购买日期"
            v-model="form.buyDate"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="expireDate" label="到期日期">
          <el-date-picker
            :disabled="true"
            value-format="yyyy-MM-dd"
            :style="fixWidth"
            placeholder="选择购买日期和折旧年限之后计算得到"
            v-model="form.expireDate"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="资产原值" prop="price">
          <el-input v-model.number="form.price" :style="fixWidth" placeholder="资产原值为资产购入时的价格" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="资产净值" prop="nowPrice">
          <el-input
            :readOnly="true"
            v-model.number="form.nowPrice"
            :style="fixWidth"
            placeholder="资产原值 *（1-购买日期到现在的月份/折旧年限）"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="折旧年限(月)">
          <el-input
            :style="fixWidth"
            :readOnly="true"
            v-model.number="form.serviceLife"
            placeholder="请输入使用期限"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="存放地点">
          <el-input :style="fixWidth" placeholder="请输入存放地点" v-model="form.storageLocation" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="useDeptId" label="使用部门">
          <dept-select
            :selectValue="form.useDeptId"
            :selectStyle="fixWidth"
            ref="userSelect"
            @select="value => handleSelect('useDeptId', value)"
            v-model="form.useDeptId"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="使用人">
          <dept-user
            :deptId="userDeptId"
            :selectStyle="fixWidth"
            :selectValue="form.useUserId"
            ref="userSelect"
            @select="value => handleSelect('useUserId', value)"
            v-model="form.useUserId"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="归属部门">
          <dept-select
            :selectValue="mdl.belongDeptId"
            :selectStyle="{ width: '300px' }"
            ref="userSelect"
            @select="value => handleSelect('belongDeptId', value)"
            v-model="form.belongDeptId"
          />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="管理员">
          <dept-user
            :deptIdManage="userDeptIdM"
            :selectStyle="fixWidth"
            :selectValue="form.manageUserId"
            ref="areaSelect"
            @select="value => handleSelect('manageUserId', value)"
            v-model="form.manageUserId"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="所在区域" style="height: 36px">
          <area-select
            :selectStyle="fixWidth"
            :selectValue="form.areaId"
            ref="areaSelect"
            @select="value => handleSelect('areaId', value)"
            v-model="form.areaId"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="标签材质" prop="lableType">
          <el-radio-group @change="handleTypeChange" v-model="form.lableType">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">普通RFID</el-radio>
            <el-radio :label="2">RFID抗金属</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="汇总物件">
          <el-radio-group
            @change="handleSummaryChange"
            :disabled="form.lableType !== 0"
            v-model="form.summaryFlag"
          >
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="form.summaryFlag">
        <el-form-item label="汇总数量">
          <el-input
            :style="fixWidth"
            type="number"
            :min="0"
            v-model="form.summaryNumber"
            placeholder="请输入汇总数量"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import moment from 'moment'
import DeptUser from '@/views/assetsNew/components/DeptUser'
import DeptSelect from '@/components/DeptSelect'
import AreaSelect from '@/views/assetsNew/components/AreaSelect'
import TypeSelect from '../components/TypeSelect'
import { getDicData, getSession } from '@/utils/util'
import { categoryTree, fuzzyQuery, supplierFuzzyQuery, createSupplier } from '@/api/assetsNew'
export default {
  components: {
    DeptUser,
    AreaSelect,
    DeptSelect,
    TypeSelect
  },
  computed: {
    computeDate() {
      const { serviceLife, buyDate } = this.form
      if (serviceLife && buyDate) {
        let buyYear = buyDate.split('-')[0]
        let buyMonth = buyDate.split('-')[1]
        let buyDay = buyDate.split('-')[2]
        if (serviceLife > 12) {
          let year = 0
          let month = 0
          if (serviceLife % 12 === 0) {
            year = serviceLife / 12
          } else {
            year = Math.floor(serviceLife / 12)
            month = serviceLife % 12
          }
          buyYear = Number(buyYear) + Number(year)
          buyMonth = Number(buyMonth) + Number(month)
        } else {
          const month = serviceLife % 12
          buyMonth = Number(buyMonth) + Number(month)
        }
        const expireDate = moment(buyYear + '-' + buyMonth + '-' + buyDay).format('YYYY-MM-DD')
        this.$set(this.form, 'expireDate', expireDate)
      }
    },
    computeNowPrice() {
      const { price, serviceLife, buyDate } = this.form
      // 计算月份差值
      const nowDate = moment(new Date()).format('YYYY-MM')
      const nowYear = nowDate.split('-')[0]
      const nowMonth = nowDate.split('-')[1]
      const oldDate = moment(buyDate).format('YYYY-MM')
      const oldYear = oldDate.split('-')[0]
      const oldMonth = oldDate.split('-')[1]
      let monthAll = 0
      let monthYear = 0
      let monthM = 0
      if (nowYear - oldYear > 0) {
        monthYear = (nowYear - oldYear) * 12
      }
      if (nowMonth - oldMonth > 0) {
        monthM = nowMonth - oldMonth
      }
      monthAll = monthYear + monthM

      if (price && serviceLife && buyDate) {
        let nowPrice = price * (1 - monthAll / serviceLife)
        if (nowPrice > 0) {
          this.$set(this.form, 'nowPrice', nowPrice)
        } else {
          this.$message.info('资产净值已小于0，资产状态已选择为报废，请知悉')
          this.$set(this.form, 'nowPrice', 0)
          this.$set(this.form, 'assetsState', 4)
          return false
        }
      }
    }
  },
  watch: {
    computeDate(n, o) {
      console.log('date n', n, o)
    },
    computeNowPrice(n, o) {
      if (n !== o) {
        console.log('n', n, o)
      }
    }
  },
  data() {
    return {
      form: {
        dirId: null,
        assetsId: null,
        assetsName: null,
        categoryId: null,
        assetsState: 0,
        brand: null,
        belongDeptId: null,
        useDeptId: null,
        useUserId: null,
        manageUserId: null,
        areaId: null,
        supplier: null,
        supplierCode: null,
        brand: '',
        factory: null,
        factoryCode: null,
        buyDate: null,
        serviceLife: null,
        expireDate: null,
        storageLocation: '',
        specification: '',
        unit: '',
        nowPrice: null,
        price: null,
        summaryFlag: 0, // 是否汇总
        lableType: null,
        summaryNumber: 1, // 汇总数量
        directoryFlag: 1,
        supplierFlag: 1,
        reviewState: 0 // 审核状态
      },
      fixWidth: {
        width: '300px'
      },
      assetsNameDisable: false,
      rules: {
        assetsName: [{ required: true, trigger: 'blur', message: '请输入固定资产名称' }],
        assetsState: [{ required: true, trigger: 'blur', message: '请输入资产状态' }],
        categoryId: [{ required: true, trigger: 'blur', message: '请选择固定资产类型' }],
        useDeptId: [{ required: true, trigger: 'change', message: '请选择使用部门' }],
        areaId: [{ required: true, trigger: 'change', message: '请选择所在区域' }],
        lableType: [{ required: true, trigger: 'blur', message: '请选择标签材质' }],
        price: [{ type: 'number', message: '请输入数字', trigger: 'blur' }],
        nowPrice: [{ type: 'number', message: '请输入数字', trigger: 'blur' }]
      },
      mdl: {},
      type: getSession('assetsType') || '', // 新增，编辑，详情三种
      disable: false,
      userDeptId: '',
      userDeptIdM: '',
      timeout: ''
    }
  },
  methods: {
    handleTypeChange(e) {
      console.log('e', e)
      if (e) {
        this.$set(this.form, 'summaryFlag', 0)
        this.$set(this.form, 'summaryNumber', null)
      }
    },
    handleSummaryChange(e) {
      if (!e) {
        this.$set(this.form, 'summaryNumber', null)
      }
    },
    async supplierSelect(value, key, code) {
      console.log('supplierSelect', value, key)
      if (value.supplierId === '-1') {
        const res = await createSupplier({ name: value.supplier })
        console.log('res', res)
        this.$set(this.form, code, res.data)
      } else {
        this.$set(this.form, code, value.supplierId)
      }
      this.$set(this.form, key, value.supplier)
      console.log('form', this.form)
    },
    nameFilter(queryString) {
      return state => {
        return state.assetsName.indexOf(queryString) >= 0
      }
    },
    supplierFilter(queryString) {
      return state => {
        return state.supplier.indexOf(queryString) >= 0
      }
    },
    async supplierQueryAsync(queryString, cb, bool, mode) {
      console.log('bool', bool)
      if (mode === 'supplier') {
        this.$set(this.form, 'supplierCode', null)
      } else {
        this.$set(this.form, 'factoryCode', null)
      }
      queryString = queryString === undefined ? null : queryString
      let results = []
      if (queryString) {
        console.log('queryString', queryString)
        let res = ''
        if (bool) {
          res = await supplierFuzzyQuery({ supplierName: queryString })
        } else {
          res = await fuzzyQuery({ assetsName: queryString })
        }
        var supplier = res.data
        if (queryString) {
          if (bool) {
            // 过滤供应商
            results = supplier.filter(this.supplierFilter(queryString))
          } else {
            results = supplier.filter(this.nameFilter(queryString))
          }
        } else {
          results = supplier
        }
        if (bool) {
          results.map(v => {
            v.value = v.supplier
          })
        } else {
          results.map(v => {
            v.value = v.assetsName
          })
        }
        // console.log('results', results)
        if (results.length === 0) {
          if (bool) {
            // 供应商
            results.push({
              value: `新增[${queryString}]`,
              supplier: queryString,
              supplierId: '-1'
            })
          }
        }

        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 1000 * Math.random())
      } else {
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 300 * Math.random())
      }
    },
    async edit(type, row) {
      this.type = type
      if (type !== 'add') {
        this.userDeptId = row.useDeptId
        this.userDeptIdM = row.belongDeptId
      }
      this.disable = type === 'detail' ? true : false
      this.form = Object.assign(this.form, row)
      this.mdl = Object.assign({}, row)
    },
    handleAssetsSelect(val) {
      this.form = { ...this.form, ...val }
      console.log('form', this.form)
      this.assetsNameDisable = true
    },
    handleSelect(key, value) {
      console.log('select', key, value)

      this.$set(this.form, key, value.key)
      if (key === 'useDeptId') {
        this.userDeptId = value.key
        this.$set(this.form, 'useUserId', null)
      }
      if (key === 'belongDeptId') {
        this.userDeptIdM = value.key
        this.$set(this.form, 'manageUserId', null)
      }
      if (key === 'manageUserId' || key === 'useUserId') {
        this.$set(this.form, key, value.userId)
      }
      if (key === 'categoryId') {
        this.$set(this.form, 'serviceLife', value.serviceLife)
      }
      console.log('form', this.form)
    },
    getFormData() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.supplier) {
            if (!this.supplierCode) {
              this.$emit('notSubmit', false, 1)
              this.$message.error('请选择一个供应商或新增一个')
              return false
            }
          }
          if (this.factory) {
            if (!this.factoryCode) {
              this.$emit('notSubmit', false, 1)
              this.$message.error('请选择一个生产厂家或新增一个')
              return false
            }
          }
          this.$emit('sendData', this.form, 1)
        } else {
          this.$emit('notSubmit', false, 1)
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.factory-autocomplete >>> .is-disabled .el-input__inner,
.el-date-editor.is-disabled >>> .el-input__inner {
  background-color: #ffffff !important;
  color: #333333 !important;
  cursor: auto;
}

.el-form-item >>> .vue-treeselect {
  width: 300px;
}
</style>
